package com.media.publish.service;


import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.baselibrary.MessageBus;
import com.baselibrary.manager.SensorsDataManager;
import com.baselibrary.utils.BitmapUtils;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.MediaFileUtils;
import com.baselibrary.utils.SpUtils;
import com.baselibrary.utils.SpanUtils;
import com.baselibrary.utils.StorageUtils;
import com.media.publish.bean.PublishBean;
import com.media.publish.utils.Config;
import com.media.publish.utils.UploadMediaUtils;
import com.okhttp.SendRequest;
import com.okhttp.callbacks.GenericsCallback;
import com.okhttp.callbacks.StringCallback;
import com.okhttp.sample_okhttp.JsonGenericsSerializator;
import com.okhttp.utils.APIUrls;
import com.okhttp.utils.OkHttpUtils;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.qiniu.pili.droid.shortvideo.PLWatermarkSetting;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import okhttp3.Call;
import okhttp3.Request;

import com.media.publish.bean.PublishReturnBean;
import com.media.publish.upload.TXUGCPublish;
import com.media.publish.upload.TXUGCPublishTypeDef;
import com.media.publish.utils.CommonBusiness;

/**
 * @author:hanke 2022/5/30
 * desc:
 */
public class UploadMediaService extends IntentService {
    public static String ACTION_PUBLISH = "action_publish";
    public static String ACTION_RE_PUBLISH = "action_re_publish";

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public UploadMediaService() {
        super("");
    }

    public static String filePath;
    public static PublishBean publishBean;
    public static boolean isPublishing;
    public String videoUrl;
    public String coverUrl;
    public String markPath = Config.VIDEO_STORAGE_DIR + "mark_" + System.currentTimeMillis() + ".mp4";//水印视频路径

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String action = intent.getAction();
        if (action.equals(ACTION_PUBLISH)) {//点击发布按钮
            isPublishing = true;
            publishBean = (PublishBean) intent.getSerializableExtra("data");
            if (publishBean.dynamicType == 2) {
//                transferVideo();
                filePath = publishBean.videoSourcePath;
                createSecurityTokenTx();
            } else if (publishBean.dynamicType == 1) {
                if (publishBean != null && publishBean.images != null && publishBean.images.size() > 0) {
                    doUploadImages();
                    SpUtils.getInstance().putDynamicDrag();
                }
            }
        } else if (action.equals(ACTION_RE_PUBLISH)) {
            isPublishing = true;
            if (publishBean != null) {
                if (publishBean.dynamicType == 1) {
                    doUploadImages();
                } else {
                    checkVideoCover();
                }
            }
        }

    }

    private void checkVideoCover() {
        if (publishBean.videoCover.isEmpty()) {
            UploadMediaUtils.uploadFile(this, filePath, fileUrl -> {
                coverUrl = fileUrl;
                doUploadVideo();
            });
        } else {
            coverUrl = publishBean.videoCover;
            doUploadVideo();
        }
    }

    private void doUploadImages() {
        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "正在上传中");
        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_start_timer, publishBean.images.size());
        UploadMediaUtils.uploadImages(publishBean.images, questionRespT -> {
            EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_progress, 90);
            EventBusUtils.sendNotify(MessageBus.msgid_notify_stop_timer);
            publishBean.imageUrls.clear();
            if (questionRespT!=null) {
                if (questionRespT.getData().size() > 0) {
                    coverUrl = questionRespT.getData().get(0).getOk();
                    for (int i = 0; i < questionRespT.getData().size(); i++) {
                        publishBean.imageUrls.add(questionRespT.getData().get(i).getOk());
                    }
                }
                doPublish();
            }else {
                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "发布失败");
            }
        });
    }

    private void doUploadVideo() {
        UploadMediaUtils.uploadVideo(filePath, new UploadMediaUtils.UploadVideoListener() {
            @Override
            public void onProgress(long uploadBytes, long totalBytes) {
                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_progress, 40 + (int) (60 * uploadBytes / totalBytes));
            }

            @Override
            public void onComplete(String videoUr, String videoCoverUrl) {
                videoUrl = videoUr;
                doPublish();
            }
        });
    }

    private void doPublish() {
        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "正在发布中");
        if (publishBean != null) {
            SendRequest.sendDynamic(
                    publishBean.districtId, (int) SpUtils.getInstance().getUserId(), publishBean.imageUrls, publishBean.address, SpUtils.getInstance().getUserToken(),
                    coverUrl, publishBean.dynamicType,
                    publishBean.provinceId, publishBean.cityId, publishBean.content, videoUrl,
                    publishBean.tagstr, "", publishBean.wineryId, publishBean.wineryCode, new GenericsCallback<PublishReturnBean>(new JsonGenericsSerializator()) {

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "发布失败");
                            isPublishing = false;
                        }

                        @Override
                        public void onResponse(PublishReturnBean response, int id) {
                            if (response.isSuccess()) {
                                isPublishing = false;
                                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "发布成功");
                                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_progress, 100);
                                EventBusUtils.sendNotify(MessageBus.msgid_notify_close_publish);
                                checkSave();
                                SensorsDataManager.Companion.getInstance().releaseDynamic(publishBean.publishType, SpanUtils.subString(publishBean.content),
                                        publishBean.imageUrls.size(), publishBean.duration, publishBean.relatedTopic, publishBean.address);
                                if (!TextUtils.isEmpty(publishBean.wineryCode)) {
                                    //酒窖发布的动态
                                    SensorsDataManager.Companion.getInstance().operatorCreateDynamic(publishBean.dynamicType == 2 ? "视频动态" : "图片动态");
                                }
                                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_publish_success, response.getData());
                                CommonBusiness.INSTANCE.updateUserInfo();
                            } else {
                                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "发布失败");
                                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_error_msg, response.getMsg());
                            }
                        }
                    });
        }
    }

    private void checkSave() {
        if (publishBean.saveMedia) {
            if (publishBean.dynamicType == 1) {
                for (String image : publishBean.images) {
                    try {
                        Bitmap bitmap = BitmapUtils.addWatermarkImg(getApplicationContext(), image, SpUtils.getInstance().getLoadUserBean().getData().getName());
                        if (bitmap != null) {
                            StorageUtils.saveBitmapToGallery(getApplicationContext(), bitmap);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                //这里需要水印之后的path
                try {
                    setWatermark(getApplicationContext());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } else {
            if (publishBean.dynamicType == 1) {
                StorageUtils.deleteTempFile();
            } else {
                File file = new File(filePath);
                file.delete();
            }
        }
    }

    public void createSecurityTokenTx() {
        OkHttpUtils.getInstance()
                .post()
                .url(APIUrls.URL_createSecurityTokenTx)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject json = new JSONObject(response);
                            boolean success = json.getBoolean("success");
                            if (success) {
                                JSONObject data = json.optJSONObject("data");
                                String signature = data.optString("signature");
                                String returnUrl = data.optString("returnUrl");
                                if (publishBean.videoCover.isEmpty()) {
                                    uploadFile(signature, returnUrl);
                                } else {
                                    coverUrl = publishBean.videoCover;
                                    uploadVideo(signature, returnUrl);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void uploadFile(final String signature, final String returnUrl) {
        String mCoverPath = MediaFileUtils.createVideoThumbnailFile(this, new File(filePath)).getPath();
        String filename = mCoverPath.substring(mCoverPath.lastIndexOf("/") + 1);
        OkHttpUtils.post()
                .addFile("file", filename, new File(mCoverPath))
                .url(APIUrls.URL_UPLOAD_FILES)
                .build()
                .execute(new StringCallback() {

                    @Override
                    public void onBefore(Request request, int id) {
                    }

                    @Override
                    public void onAfter(int id) {
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "上传失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject object = new JSONObject(response);
                            coverUrl = object.getString("ok");
                            uploadVideo(signature, returnUrl);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                    }
                });
    }

    private void uploadVideo(String signature, final String returnUrl) {
        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_progress, 40);
        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_status, "正在上传中");
        TXUGCPublish mVideoPublish = new TXUGCPublish(getApplicationContext(), "independence_android");
        mVideoPublish.setListener(new TXUGCPublishTypeDef.ITXVideoPublishListener() {
            @Override
            public void onPublishProgress(long uploadBytes, long totalBytes) {
                EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_total_progress, 40 + (int) (60 * uploadBytes / totalBytes));
            }

            @Override
            public void onPublishComplete(TXUGCPublishTypeDef.TXPublishResult result) {
                if (!TextUtils.isEmpty(result.videoId)) {
                    videoUrl = returnUrl + result.videoId;//视频URL
                    doPublish();
                }
            }
        });

        TXUGCPublishTypeDef.TXPublishParam param = new TXUGCPublishTypeDef.TXPublishParam();
        param.signature = signature;
        param.videoPath = filePath;
        mVideoPublish.publishVideo(param);
    }


    /**
     *
     */
    public void setWatermark(Context context) {
        PLShortVideoTranscoder mShortVideoTranscoder = new PLShortVideoTranscoder(context, filePath, markPath);
        PLMediaFile mMediaFile = new PLMediaFile(filePath);
        PLWatermarkSetting mWatermarkSetting = new PLWatermarkSetting();
        mWatermarkSetting.setBitmap(BitmapUtils.createView("酣享@" + SpUtils.getInstance().getLoadUserBean().getData().getName()+"哈哈哈哈哈哈哈"));
        mWatermarkSetting.setPosition(1f, 1f);
        mWatermarkSetting.setAlpha(255);
        mShortVideoTranscoder.setWatermark(mWatermarkSetting);
        mShortVideoTranscoder.transcode(mMediaFile.getVideoWidth(), mMediaFile.getVideoHeight(), mMediaFile.getVideoBitrate(), 0, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String s) {
                //成功
                new File(filePath).delete();//把 拍摄or 编辑 的文件删除，然后更新水印视频的文件
                if (!TextUtils.isEmpty(markPath)) {
                    File file = new File(markPath);
                    if (file.exists()) {
                        Uri uri = Uri.fromFile(file);
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                        //如果是拍摄视频，下面代码是有用的，如果不是，是没用。。。如果是从相册选择的视频，视频已经处于相册中了，所以下面的代码没用
                        Uri sourceUri = Uri.fromFile(new File(publishBean.videoSourcePath));
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, sourceUri));
                    }
                }
            }

            @Override
            public void onSaveVideoFailed(int i) {
                //失败
            }

            @Override
            public void onSaveVideoCanceled() {
                //取消
            }

            @Override
            public void onProgressUpdate(float v) {
                //进行中
            }
        });
    }

}
